<!DOCTYPE html>
<html lang="en-US">
  <head>
    <link href="/assets/index.css" rel="stylesheet" type="text/css" />
    <script crossorigin="anonymous" src="https://unpkg.com/@babel/standalone@7.8.7/babel.min.js"></script>
    <script crossorigin="anonymous" src="https://unpkg.com/react@16.8.6/umd/react.development.js"></script>
    <script crossorigin="anonymous" src="https://unpkg.com/react-dom@16.8.6/umd/react-dom.development.js"></script>
    <script crossorigin="anonymous" src="/test-harness.js"></script>
    <script crossorigin="anonymous" src="/test-page-object.js"></script>
    <script crossorigin="anonymous" src="/__dist__/webchat-es5.js"></script>
    <style type="text/css">
      .scroll-panel {
        left: 0;
        position: fixed;
        top: 0;
      }
    </style>
  </head>
  <body>
    <main id="webchat"></main>
    <script type="text/babel" data-presets="env,stage-3,react">
      const {
        React: { useCallback, useLayoutEffect, useRef, useState },
        WebChat: {
          Components: { BasicWebChat, Composer },
          hooks: { useObserveScrollPosition, useScrollTo, useSendMessage }
        }
      } = window;

      function generateTranscript() {
        const messages = [
          'Do incididunt qui sit nulla dolor.',
          'Ipsum dolor laborum veniam sunt irure nulla aliquip minim ad veniam culpa sit ut.',
          'Labore ut ex anim in nisi enim deserunt anim minim esse veniam.',
          'Lorem amet occaecat voluptate fugiat elit cillum.',
          'Sit et velit qui laboris et elit eu pariatur velit occaecat.',
          'Nostrud minim deserunt excepteur elit aliquip excepteur.',
          'Laboris pariatur minim ad incididunt.',
          'Reprehenderit sint id elit laboris nisi ipsum pariatur et id deserunt dolore.',
          'Quis dolor ut dolor qui.',
          'Fugiat commodo ipsum irure deserunt duis ea est amet Lorem esse eiusmod.',
          'Magna occaecat enim magna laboris sunt consequat esse elit ipsum esse quis culpa amet.',
          'Laborum officia est elit officia voluptate dolore elit veniam aute velit.',
          'Et esse sint incididunt irure et amet deserunt consectetur dolor.',
          'Ipsum adipisicing nisi nulla eiusmod commodo ad enim veniam velit.',
          'Consectetur labore adipisicing do dolor dolor eiusmod sint irure in labore ullamco incididunt voluptate.',
          'Duis voluptate elit tempor quis consequat incididunt excepteur anim in.',
          'Aliquip cupidatat exercitation magna aute nostrud fugiat deserunt.',
          'Nulla eu do duis consequat sint irure proident cupidatat duis.',
          'Ipsum laborum commodo sint tempor fugiat esse est sit officia qui cupidatat nisi minim.',
          'Veniam consequat ut anim consequat ea incididunt ipsum proident duis veniam irure consequat exercitation.\n\nVoluptate dolor nostrud ipsum amet in velit cupidatat veniam voluptate ipsum.\n\nPariatur ipsum eiusmod deserunt commodo elit aute in velit proident.\n\nCulpa amet deserunt excepteur ex quis Lorem commodo ipsum sint consectetur id.\n\nAliquip officia qui ea cillum duis labore consectetur sunt excepteur labore.\n\nElit adipisicing et consectetur occaecat sint nulla Lorem id anim Lorem.\n\nPariatur officia velit officia do nisi cupidatat enim nulla et sit.\n\nDuis anim Lorem reprehenderit mollit occaecat sunt.\n\nLorem cupidatat id culpa anim velit qui irure.\n\nVoluptate aute incididunt cillum culpa laborum est sunt et ea proident minim non.\n\nId Lorem eiusmod amet sint nulla velit ullamco tempor incididunt pariatur.\n\nElit elit fugiat dolore amet dolor voluptate.\n\nEa pariatur nulla dolor excepteur enim sit aliquip incididunt laboris pariatur fugiat commodo officia minim.\n\nConsequat elit amet minim consectetur tempor.\n\nPariatur excepteur consectetur adipisicing quis laborum.\n\nIn aute consectetur ullamco eiusmod reprehenderit consequat non aliquip consequat eiusmod et laboris.\n\nMagna amet nulla do nulla ea ad do occaecat adipisicing.\n\nConsequat quis laborum nisi ut exercitation reprehenderit cupidatat proident incididunt est eiusmod ea.\n\nAdipisicing aliqua elit nostrud sint magna aliqua nisi deserunt ex occaecat velit ipsum duis.\n\nEnim veniam sunt cillum voluptate laborum do.\n\nVeniam ea aute reprehenderit et ad reprehenderit non do deserunt minim eu elit.\n\nAnim irure fugiat nostrud occaecat amet sint pariatur irure cupidatat commodo fugiat Lorem minim deserunt.\n\nAd consectetur excepteur enim nisi adipisicing.\n\nMollit duis est ipsum nulla aliquip.\n\nSunt reprehenderit quis in ea eu tempor fugiat ad dolore ea adipisicing consectetur elit.\n\nConsequat minim culpa ea sit ullamco ex id exercitation.\n\nCulpa cillum non ipsum eu Lorem nostrud nostrud consequat anim in culpa nostrud.\n\nNostrud nisi quis et Lorem aliquip anim deserunt culpa.\n\nSunt cupidatat commodo quis elit consequat ullamco irure id tempor.\n\nCommodo dolor officia magna amet aliqua proident qui ipsum voluptate.\n\nDo officia cupidatat id in proident.'
        ];

        return messages.map((text, index) => {
          const fromUser = index % 2;

          return {
            channelData: {
              'webchat:sequence-id': index,
              ...(fromUser
                ? {
                    channelData: {
                      clientActivityID: index + '',
                      state: 'sent'
                    }
                  }
                : {})
            },
            from: { role: fromUser ? 'user' : 'bot' },
            id: index + '',
            text: `#${index}: ${text}`,
            timestamp: 0,
            type: 'message'
          };
        });
      }

      run(async function () {
        const directLine = testHelpers.createDirectLineWithTranscript(generateTranscript());
        const store = testHelpers.createStore();

        let lastScrollPosition;

        const RunFunction = ({ fn }) => {
          fn();

          return false;
        };

        const ScrollPanel = () => {
          const ref = useRef();

          useObserveScrollPosition(position => {
            lastScrollPosition = position;
          });

          return <div className="scroll-panel" ref={ref}></div>;
        };

        const WebChat = ({ children, className }) => {
          return (
            <Composer directLine={directLine} store={store}>
              <BasicWebChat className={className} />
              {children}
              <ScrollPanel />
            </Composer>
          );
        };

        const renderWithFunction = fn => {
          const deferreds = [createDeferred(), createDeferred()];

          ReactDOM.render(
            <WebChat className="webchat">
              <RunFunction fn={() => deferreds[0].resolve(fn && fn())} key={Date.now() + ''} />
            </WebChat>,
            document.getElementById('webchat'),
            deferreds[1].resolve
          );

          return Promise.all(deferreds.map(({ promise }) => promise));
        };

        window.renderWithFunction = renderWithFunction;

        await renderWithFunction();

        await pageConditions.uiConnected();

        // Wait until the view is not sticky.
        await new Promise(resolve => setTimeout(resolve, 200));
        await pageConditions.scrollToBottomCompleted();

        // "12" should appears right above the send box.
        await renderWithFunction(() => useScrollTo()({ activityID: '12' }));
        await host.snapshot();

        // When on top, it should always return the first activity in the transcript.
        await renderWithFunction(() => useScrollTo()({ scrollTop: 0 }));
        await new Promise(resolve => setTimeout(resolve, 200)); // Wait until "scroll" event
        expect(lastScrollPosition).toHaveProperty('activityID', '0');
        expect(lastScrollPosition).toHaveProperty('scrollTop', 0);
        await host.snapshot();

        // Since "19" is a super-long activity, it should appears on the top of the page.
        await renderWithFunction(() => useScrollTo()({ activityID: '19' }));
        await host.snapshot();
      });
    </script>
  </body>
</html>
